import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import devboard.dbutil.MongoUtil;

@WebServlet("/PlanningHandler")
public class PlanningHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
    public PlanningHandler() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	if(request.getParameter("reason").equals("deleteAll")){
    		DBCollection tempTasks=MongoUtil.getCollection("TempTasks");
    		tempTasks.remove(new BasicDBObject());
    	}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String reason=request.getParameter("reason");
		if(reason==null){
			importFromCSV(request);
			response.sendRedirect("Planning.jsp");
		}else if(reason.equals("saveState")){
			InputStreamReader in = new InputStreamReader(request.getInputStream());
			StringBuilder s=new StringBuilder();
			int c;
			while((c=in.read())>=0){
				s.append((char)c);
			}
			s.deleteCharAt(s.length()-1);
			String[] ids=s.toString().split(",");
			DBCollection tempTasks=MongoUtil.getCollection("TempTasks");
			for(int i=0;i<ids.length;i+=3){
				DBObject task=tempTasks.findOne(new BasicDBObject("_id", ids[i]));
				if(task!=null){
					task.put("estimate", ids[i+2]);
					task.put("checked", ids[i+1]);
					tempTasks.update(new BasicDBObject("_id", ids[i]),task);
				}
			}
		}else if(reason.equals("addToBoard")){
			InputStreamReader in = new InputStreamReader(request.getInputStream());
			StringBuilder s=new StringBuilder();
			int c;
			while((c=in.read())>=0){
				s.append((char)c);
			}
			s.deleteCharAt(s.length()-1);
			String[] ids=s.toString().split(",");
			DBCollection tempTasks=MongoUtil.getCollection("TempTasks");
			DBCollection tasks=MongoUtil.getCollection("Tasks");
			DBObject[] dbos=new DBObject[ids.length]; 
			for(int i=0;i<ids.length;i+=1){
				DBObject task=tempTasks.findOne(new BasicDBObject("_id", ids[i]));
				if(task!=null){
					task.put("_id",""+(System.currentTimeMillis()-Integer.parseInt(String.valueOf(task.get("_id")))));
					task.put("userId", "nobody");
					task.put("reproduced", "no");
					task.put("inProgress", "no");
					task.put("delivered", "no");
					task.put("successfully", "no");
					task.put("timeCreation", System.currentTimeMillis());
					task.put("projectId", "");
					dbos[i]=task;
				}
			}
			tasks.insert(dbos);
		}else if(reason.equals("sendEmail")){
			InputStreamReader in = new InputStreamReader(request.getInputStream());
			StringBuilder s=new StringBuilder();
			int c;
			while((c=in.read())>=0){
				s.append((char)c);
			}
			s.deleteCharAt(s.length()-1);
			sendTo(request.getParameter("recipient"),s.toString());
		}
	}
	
	private void sendTo(String recipient, String what)throws IOException{
		String[] ids=what.toString().split(",");
		DBCollection tempTasks=MongoUtil.getCollection("TempTasks");
		StringBuilder content=new StringBuilder("sub id\testimate\tlink\n");
		for(int i=0;i<ids.length;i++){
			DBObject task=tempTasks.findOne(new BasicDBObject("_id", ids[i]));
			if(task!=null){
				content.append(task.get("_id")+"\t"+task.get("estimate")+"\t"+task.get("link")+"\n");
			}
		}
		//send
        try {
        	Properties props = new Properties();
        	props.put("mail.smtp.starttls.enable","true");
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.host", "smtp.mail.ru");
            props.put("mail.smtp.auth", "true");

            Authenticator auth = new Authenticator() {
            	@Override
            	protected PasswordAuthentication getPasswordAuthentication() {
            		String username = "laksap@mail.ru";
                    String password = "kasjbgHUWWfo__-";
                    return new PasswordAuthentication(username, password);
            	}
			};
            Session mailSession = Session.getDefaultInstance(props, auth);
            Transport transport = mailSession.getTransport();
            MimeMessage message = new MimeMessage(mailSession);
            message.setText(content.toString());
            message.setFrom(new InternetAddress("laksap@mail.ru"));
            message.addRecipient(Message.RecipientType.TO,
                 new InternetAddress(recipient));

            transport.connect();
            transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
            transport.close();
        }
        catch (MessagingException e) {
        	e.printStackTrace();
        }
	}
	
	private void importFromCSV(HttpServletRequest request) throws ServletException, IOException {
		InputStreamReader in = new InputStreamReader(request.getInputStream());
		StringBuilder s=new StringBuilder();
		int c;
		while((c=in.read())>=0){
			s.append((char)c);
		}
		s.delete(0, s.indexOf("\n")+1);
		s.delete(0, s.indexOf("\n")+1);
		s.delete(0, s.indexOf("\n")+1);
		s.delete(s.lastIndexOf("\n"), s.length());
		s.delete(s.lastIndexOf("\n"), s.length());
		
		String[] temp=s.toString().trim().split("\n");
		String[][] str=new String[temp.length][];
		for(int i=0;i<temp.length;i++){
			str[i]=temp[i].split(",");
		}
		
		String[][] taskArray=new String[str.length-1][5];
		for(int i=0;i<str[0].length;i++){
			if(str[0][i].equals("Sub ID")){
				for(int j=0;j<taskArray.length;j++){
					taskArray[j][0]=str[j+1][i];
				}
			}
		}
		for(int i=0;i<str[0].length;i++){
			if(str[0][i].equals("Team")){
				for(int j=0;j<taskArray.length;j++){
					taskArray[j][1]=str[j+1][i];
				}
			}
		}
		for(int i=0;i<str[0].length;i++){
			if(str[0][i].equals("Service Type")){
				for(int j=0;j<taskArray.length;j++){
					taskArray[j][2]=str[j+1][i];
				}
			}
		}
		for(int i=0;i<str[0].length;i++){
			if(str[0][i].equals("RFP Title")){
				for(int j=0;j<taskArray.length;j++){
					taskArray[j][3]=str[j+1][i];
				}
			}
		}
		for(int i=0;i<str[0].length;i++){
			if(str[0][i].equals("RFP Link")){
				for(int j=0;j<taskArray.length;j++){
					taskArray[j][4]=str[j+1][i];
				}
			}
		}
		
		DBCollection tempTasks=MongoUtil.getCollection("TempTasks");
		BasicDBObject[] docs=new BasicDBObject[taskArray.length];
		for(int i=0;i<taskArray .length;i++){
			docs[i]=new BasicDBObject();
			docs[i].put("_id", taskArray[i][0]);
			docs[i].put("project", taskArray[i][1]); 
			docs[i].put("serviceType", taskArray[i][2]);
			docs[i].put("name", taskArray[i][3]);
			docs[i].put("link", taskArray[i][4]);
			docs[i].put("estimate", "5");
			docs[i].put("checked", "");
		}
		tempTasks.insert(docs);
	}
}
